//
//  HomePageViewController.m
//  SchoolTimetable
//
//  Created by 梦里都是梦 on 16/1/6.
//  Copyright (c) 2016年 Yuanlinqian. All rights reserved.
//

#import "HomePageViewController.h"
#import "HomePageViewCell.h"
#import "NewsModel.h"
#import "TableFooterView.h"
#import "WebViewController.h"
@interface HomePageViewController ()
{
    UIRefreshControl * _refreshControl;
    NSInteger _currentPage;
    TableFooterView * _tableFooterView;
}

@property (nonatomic,strong) NSMutableArray * dataArray;


@end

@implementation HomePageViewController


-(NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc]init];
    }
    return _dataArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self customView];
    [self registerCell];
    [self firstLoad];
    self.tableView.rowHeight = 170;
    self.navigationItem.title = @"校园淘";

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
-(void)firstLoad
{
    // 让刷新控件请求动画并刷新数据
    [_refreshControl beginRefreshing];
    [self headerRefresh:_refreshControl];
    
}
-(void)customView
{
    _refreshControl = [[UIRefreshControl alloc]init];
    [self.tableView addSubview:_refreshControl];
    _refreshControl.tintColor = [UIColor redColor];
    [_refreshControl addTarget:self action:@selector(headerRefresh:) forControlEvents:UIControlEventValueChanged];
    
    _tableFooterView = [[TableFooterView alloc]initWithFrame:CGRectMake(0, 0, 320, 44)];
    // 设置UITableView的FooterView
   self.tableView.tableFooterView = _tableFooterView;
    UITapGestureRecognizer * tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(requestMore:)];
    [_tableFooterView addGestureRecognizer:tapGesture];

}
-(void)requestMore:(UITapGestureRecognizer *)sender
{
    if ([_tableFooterView respondsToTouch]) {
        _tableFooterView.status = RefreshStatusLoading;
        _currentPage++;
        [self requestDataOnPage:_currentPage];
    }
}
-(void)headerRefresh:(UIRefreshControl *)sender
{
    _currentPage = 1;
    // 请求数据
    [self requestDataOnPage:_currentPage];
    
}
-(void)registerCell
{
    [self.tableView registerNib:[UINib nibWithNibName:@"HomePageViewCell" bundle:nil] forCellReuseIdentifier:@"HomePageViewCell"];

}
-(void)requestDataOnPage:(NSInteger )currentPage
{
    // 创建NSURLSession对象,获取单例对象
//    ?device_type=ios&page=2&per_page=20&request_time=1452787081.781031&token=QJNMMANKBGTSOAKHDSNMAT&version=7.1.5
    NSString * urlStr = [NSString stringWithFormat:@"%@?device_type=%@&page=%ld&per_page=%d&request_time=%@&token=%@&version=%@",GEZI_URL,@"ios",currentPage,20,@"1452787081.781031",@"QJNMMANKBGTSOAKHDSNMAT",@"7.1.5"];
    NSURLSession * session = [NSURLSession sharedSession];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
    NSURLSessionDataTask * dataTask =  [session dataTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]] completionHandler:^(NSData * data,NSURLResponse * response,NSError * Error){
                    if (data) {
                                                NSDictionary * resoponseDict =  [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                                                NSArray * dealsArray = resoponseDict[@"deals"];
                        if (dealsArray.count == 0) {
                            
                            dispatch_async(dispatch_get_main_queue(), ^{
                                [SVProgressHUD showInfoWithStatus:@"没有更多"];
                                _tableFooterView.status = RefreshStatusNotMore;
                            });
                            
                            return;
                        }
                                                for (NSDictionary * dic in dealsArray) {
                                                    NewsModel * model = [[NewsModel alloc]init];
                                                    [model setValuesForKeysWithDictionary:dic];
                                                    [self.dataArray addObject:model];
                                                }
                        
                                                dispatch_async(dispatch_get_main_queue(), ^{
                                                    [self.tableView reloadData];
                                                    [_refreshControl endRefreshing];
                                                     _tableFooterView.status = RefreshStatusMore;
                                                });
                                            }
        else
        {
            if (_currentPage == 1) {
                [_refreshControl endRefreshing];
            }
            else
            {
                _currentPage--;
                _tableFooterView.status = RefreshStatusError;
            }

        
        }
                                        }];

    
    // 启动请求
    [dataTask resume];
    });


}

#pragma mark - Table view data source
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
    
}
//- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
//    // Return the number of sections.
//    return 10;
//}
//
//- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//    // Return the number of rows in the section.
//    return 0;
//}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HomePageViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HomePageViewCell" forIndexPath:indexPath];
    NewsModel * model = self.dataArray[indexPath.row];
    [cell.newsPicImgView sd_setImageWithURL:[NSURL URLWithString:model.cover]];
    cell.newsTitleLabel.text = model.title;
    return cell;
}
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (scrollView.contentOffset.y + scrollView.frame.size.height > scrollView.contentSize.height) {
        [self requestMore:nil];
    }
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{


    NewsModel * model = self.dataArray[indexPath.row];
    WebViewController * webVc = [[WebViewController alloc]init];
    webVc.url  = model.url;
    [self.navigationController pushViewController:webVc animated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
